package com.service.Impl;


import cn.hutool.core.lang.Snowflake;
import com.mapper.SysPermissionMapper;
import com.mapper.SysRoleMapper;
import com.mapper.SysUserMapper;
import com.pojo.dto.Message;
import com.pojo.entity.SysPermission;
import com.pojo.entity.SysRole;
import com.pojo.entity.SysUser;
import com.pojo.vo.SysUserVo;
import com.pojo.vo.UserVo;
import com.service.UserService;
import com.util.PasswordUtil;
import com.util.PojoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service(value = "UserService")
public class UserServiceImpl implements UserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysPermissionMapper sysPermissionMapper;
    @Autowired
    Snowflake snowflake;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public Boolean auth(String username) {
        SysUser user = sysUserMapper.findByName(username);
        if (user == null) return true;
        return false;
    }

    @Override
    public boolean auth(String username, String password) {
        SysUser user = sysUserMapper.findByName(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) return true;
        return false;
    }

    @Override
    public Message<SysUserVo> add(SysUserVo userVo) {
        SysUser sysUser = PojoUtil.copyObject(userVo, SysUser.class);
        sysUser.setId(snowflake.nextId());
        sysUser.setCreateTime(new Date().getTime());
        sysUser.setUpdateTime(new Date().getTime());
        sysUser.setPassword(PasswordUtil.getEncryptPassword(sysUser.getPassword()));
        int i = sysUserMapper.insert(sysUser);

        if (i == 0) return Message.errorMessage("1001", "添加失败");
        else return Message.successMessage(1L, userVo);
    }

    @Override
    public List<Long> findAllUserIds() {
        return sysUserMapper.findAllUserIds();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserMapper.findByName(username);
        List<SysRole> roleList = sysRoleMapper.selectByUserId(user.getId()); // 查询是当前用户的所有角色
        List<Long> roleIds = roleList.stream().map(r -> r.getId()).collect(Collectors.toList());
        List<SysPermission> pList = sysPermissionMapper.selectByRoleIdList(roleIds);
        UserVo userVo = new UserVo(user, roleList, pList);
        return userVo;
    }
}
